package tk.hongbo.rainbow

import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import tk.hongbo.rainbow.core.SoundPlayer
import tk.hongbo.rainbow.databinding.ActivityMainBinding
import kotlin.random.Random

const val COUNT_TIME = 1500L

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    @Volatile
    private var STATUS: Int = 0 //游戏状态 0:暂停 1:开始

    @Volatile
    private var PLAY_STATUS = 1 //准备音播放

    @Volatile
    private var thisRes: Int = R.raw.a0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener { switchClick() }
    }

    @Synchronized
    private fun switchClick() {
        if (STATUS == 0) {
            STATUS = 1
            timer.start()
            binding.button.text = "游戏中"
        } else {
            over()
        }
    }

    private fun over() {
        STATUS = 0
        PLAY_STATUS = 1
        timer.cancel()
        binding.button.text = "游戏结束"
    }

    private val timer = object : CountDownTimer(Int.MAX_VALUE.toLong(), COUNT_TIME) {
        override fun onTick(p0: Long) {
            playSound()
        }

        override fun onFinish() {
        }
    }

    private fun playSound() {
        if (PLAY_STATUS == 0) {
            thisRes = getRes()
            PLAY_STATUS = 1
        } else {
            thisRes = R.raw.a0
            PLAY_STATUS = 0
        }
        SoundPlayer.getInstance().play(this, thisRes)
        Handler().postDelayed({
            if (thisRes == R.raw.a4) {
                timer.cancel()
                over()
            }
        }, COUNT_TIME)
    }

    /**
     * 播放的音频文件
     */
    private fun getRes(): Int {
        val sequence = Random.nextInt(5)
        return when (sequence) {
            1 -> R.raw.a1
            2 -> R.raw.a2
            3 -> R.raw.a3
            4 -> R.raw.a4
            else -> R.raw.a0
        }
    }

    override fun onDestroy() {
        SoundPlayer.getInstance().release()
        super.onDestroy()
    }
}